package com.simon.system.controller;

import java.util.Date;
import java.util.List;

import com.simon.exception.CheckException;
import com.simon.exception.OperationFailedException;
import com.simon.http.model.DoResponse;
import com.simon.http.model.PageResponse;
import com.simon.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.simon.http.model.PResponse;
import com.simon.http.model.UserQuery;
import com.simon.system.model.User;
import com.simon.system.service.UserService;
import com.simon.token.TokenValidate;
import com.simon.utils.SystemCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @ClassName UserController
 * @Description 用户控制层
 * @Author Jiajie.Mao
 * @Date 2018/6/5 9:38
 * @Version 1.0
 **/
@RestController
@RequestMapping(value = "/user")
@Api(value = "user", tags = {"用户接口"})
public class UserController {

    @Autowired
    private UserService userService;


    @ApiOperation(value = "添加用户", notes = "根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户对象", required = true, dataType = "User")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public DoResponse<?> addUser(@RequestBody User user) {
        User dUser = userService.findByUsername(user.getUsername());
        if (dUser != null) {
            throw new OperationFailedException("该用户已存在");
        } else {
            //插入数据库
            int res = userService.addUser(user);
            //获取数据库生成的ID
            User addUser = userService.findByUsername(user.getUsername());
            if (res > 0) {
                //设置用户角色
                userService.setRoles(addUser.getId(), user.getRoleId());
                //设置用户部门
                userService.setDepts(addUser.getId(), user.getDeptId());
                return new DoResponse<>();
            } else {
                throw new OperationFailedException("添加用户失败");
            }
        }
    }


    @ApiOperation(value = "查询用户", notes = "根据id获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @TokenValidate
    public DoResponse<?> getUserById(@RequestParam int id) {

        User user = userService.getUserById(id);
        if (user != null) {
            return new DoResponse<>(user);
        } else {
            throw new OperationFailedException();
        }
    }


    @ApiOperation(value = "获取用户列表", notes = "")
    @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @TokenValidate
    public DoResponse<?> findAllUser() {
        List<User> users = userService.findAllUser();
        if (users.size() > 0) {
            return new DoResponse<>(users);
        } else {
            throw new OperationFailedException();
        }
    }


    @ApiOperation(value = "查询用户列表", notes = "根据自定义条件分页查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户名", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "pageNum", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "pageSize", dataType = "int", defaultValue = "10")
    })
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @TokenValidate
    public PageResponse<?> queryUsers(@RequestParam String username, @RequestParam int pageNum, @RequestParam int pageSize) {
        if (pageNum == 0 || pageSize == 0) {
            throw new CheckException("页码和单页条目必输");
        }
        UserQuery userQuery = new UserQuery(pageNum, pageSize, username);
        List<User> users = userService.queryUsers(userQuery);
        PResponse bPage = userService.calPage(userQuery);
        if (users.size() > 0) {
            return new PageResponse<>(users, users.size(), bPage.getTotalElements(), bPage.getTotalPage());
        } else {
            throw new OperationFailedException();
        }
    }


    @ApiOperation(value = "删除用户", notes = "根据用户id删除用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @TokenValidate
    public DoResponse<?> deleteUser(@RequestParam int id) {
        int res = userService.deleteUser(id);
        if (res > 0) {
            return new DoResponse<>();
        } else {
            throw new OperationFailedException();
        }
    }


    @ApiOperation(value = "更新用户", notes = "更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "user", value = "用户对象", required = true, dataType = "User")
    })
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> updateUser(@RequestParam int id, @RequestBody User user) {
        User dUser = userService.getUserById(id);

        if (dUser != null) {
            int res = userService.updateUser(dUser, user);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        } else {
            throw new OperationFailedException("不存在此数据");
        }

    }

    @ApiOperation(value = "修改密码", notes = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "oldPwd", value = "旧密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPwd", value = "新密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "rePwd", value = "重复密码", required = true, dataType = "String")
    })
    @RequestMapping(value = "/changePwd", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> changePassword(@RequestParam int id, @RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
        //判断新密码不能为空
        if (newPwd == null || rePwd == null || "".equals(newPwd) || "".equals(rePwd)) {
            throw new CheckException("新密码不能为空");
        }

        //判断两次密码是否一致
        if (!rePwd.equals(newPwd)) {
            throw new CheckException("两次新密码不一致");
        }

        //判断用户是否存在和校验密码是否一致 !user.getPassword().equals(Utils.encodeMD5(oldPwd))
        User user = userService.getUserById(id);
        if (user == null) {
            throw new OperationFailedException("用户不存在");
        } else {
            if (!Md5Utils.validPassword(oldPwd, user.getPassword())) {
                throw new OperationFailedException("密码错误");
            } else {
                user.setLastpasswordreset(new Date());
                user.setPassword(Md5Utils.getEncryptedPwd(newPwd));
                user.setModifytime(new Date());
                int res = userService.changePassword(user);
                if (res > 0) {
                    return new DoResponse<>();
                } else {
                    throw new OperationFailedException();
                }
            }
        }

    }

    @ApiOperation(value = "冻结用户", notes = "冻结用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/freeze", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> freezeUser(@RequestParam int id) {
        User user = userService.getUserById(id);
        if (user == null) {
            throw new CheckException("用户不存在");
        } else {
            int res = userService.freezeUser(user);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        }
    }

    @ApiOperation(value = "取消冻结用户", notes = "取消冻结用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int")
    })
    @RequestMapping(value = "/unfreeze", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> unfreezeUser(@RequestParam int id) {
        User user = userService.getUserById(id);
        if (user == null) {
            throw new CheckException("用户不存在");
        } else {
            int res = userService.unFreezeUser(user);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        }
    }

    @ApiOperation(value = "设置角色", notes = "设置角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "身份令牌", paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "int"),
            @ApiImplicitParam(name = "roleIds", value = "角色ids", dataType = "String")
    })
    @RequestMapping(value = "/setRole", method = RequestMethod.PUT)
    @TokenValidate
    public DoResponse<?> setRoles(@RequestParam int id, @RequestParam String roleIds) {
        User user = userService.getUserById(id);
        if (user == null) {
            throw new CheckException("用户不存在");
        } else {
            int res = userService.setRoles(id, roleIds);
            if (res > 0) {
                return new DoResponse<>();
            } else {
                throw new OperationFailedException();
            }
        }
    }


}
